<?php

class ReferencesController extends AppController {

var $name = 'References';
	var $uses = array('User', 'Reference', 'Application', 'Attachment');
	
	var $lightFields = array(
				'id', 
				'uid',
				'created', 
				'modified',
				'application_id',
				'file_name',
				'file_size',
				'file_date',
				'lastname',
				'firstname',
				'title',
				'phone',
				'email',
				'ferpa_waived',
				'use_web',
				'knowledge_length',
				'has_grad_prog', 
  			'would_admit', 
  			'not_admit_info',
  			'intel_ability',
				'academic_prep',
				'maturity',
				'interpersonal_skills',
				'oral_comm',
				'written_comm', 
				'finishes_tasks',
				'creative_think',
				'independent_work',
				'professional_clinic', 
				'motivation', 
				'originality',
				'initiative',
				'critical_thinking',
				'emot_stability', 
				'perseverance',
				'overall',
				'complete',
				'email_sent',
				'Application.id',
				'Application.firstname',
				'Application.lastname'
			);
	
function beforeFilter() {
	parent::beforeFilter();
	$this->Auth->Allow('evaluate', 'viewLetter', 'deleteLetter');
	if (isset($this->passedArgs[0]) && $this->Auth->user('group_id') == 2) {
			$model = ($this->params['action'] == 'delete')? 'Reference': 'Application';
  		$aco = $this->Acl->Aco->findByModelAndForeignKey($model, $this->passedArgs[0]);
    	$aro = $this->Acl->Aro->findByModelAndForeignKey('User', $this->Auth->user('id'));
    	if (!$this->Acl->check($aro['Aro'], $aco['Aco'])) {
      	$this->Session->setFlash($this->Auth->authError, 'flash_failure');
        $this->redirect($this->referer());
    	}
		}
}
	
function index ($app_id=null) {
		
		if (!$app_id) {
			$this->Session->setFlash(__('No valid application id: Please contact gradsec@psych.uoregon.edu', true));
			$this->redirect($this->referer());
		}
		
		$data = $this->Reference->findAllByApplicationId($app_id, array(
																											'id', 'firstname', 'lastname', 'phone', 'email', 'complete'), 
																											null, null, null, 0);
		$this->set('app_id', $app_id); 		
		$this->set(compact('data'));
		$this->set('info', $this->_getContentMsg('references_info'));
		$this->set('ferpa', $this->_getContentMsg('references_ferpa'));
		$this->set('use_web', $this->_getContentMsg('references_use_web'));
		
	} //end index
	
	
/**
*add a Reference
*/
function add($app_id = null) {
	
	if (!empty($this->data)) {
		$this->Reference->create();
		$this->Reference->set($this->data);
		
		$uid = $this->_generateToken();
		$this->Reference->set('uid', $uid);
		
		if($this->Reference->validates() 
			 && $this->Reference->save($this->data, array('validate' => false))) {
			$this->Reference->read($this->lightFields);
			$id = $this->Reference->id;
			$app_id = $this->Reference->data['Reference']['application_id'];
			$err = false;
			if($this->Reference->data['Reference']['use_web']) {
				//Grab the email content.
				$message =  $this->_getContentMsg('reference_request_email');
				//Now email the student.
				if (!$this->_sendEmailMsg($this->data['Reference']['email'], 
							  'UO Department of Psychology Online Recommendation Request', 
							  $message, array( 
																 	'full_name' => $this->Reference->data['Application']['firstname']
																								 . ' ' 
																								 . $this->Reference->data['Application']['lastname'],
																	'base_url' => FULL_BASE_URL,
																	'url' => $this->Reference->id . '/' . $uid
																 )
					 		 								 )
				) {
					$this->Session->setFlash(__('Unable to send reference request email.', true), 
																			'flash_failure', null, 'rl');
					$err = true;
				} else {
					$this->Reference->query('UPDATE `references` SET `email_sent` = 1 WHERE id = '. $this->Reference->id . ';');
				}
			}
			if(!$err) {
				$this->Application->change_status($app_id, 'references', 1, '');
				$this->Session->setFlash("Successfully Updated Reference List", 'flash_success', null, 'rl');
			}
		} else {
			$errors = $this->Reference->invalidFields();
			$flash = 'Error Saving Reference; <br />';
			foreach($errors as $error) {
				$flash .= $error . '<br />';
			}
			$this->Session->setFlash(__($flash, true), 'flash_failure', null, 'rl');
		}
	} else {
		$this->Session->setFlash(__('Error encountered, No Data.', true), 'flash_failure', null, 'rl');
	}
	
	$data = $this->Reference->findAllByApplicationId($app_id, array(
																											'id', 'firstname', 'lastname', 'phone', 'email', 'complete'), 
																											null, null, null, 0);
	$this->set('app_id', $app_id); 		
	$this->set(compact('data'));
	
	if ($this->RequestHandler->isAjax()) {
		$this->render('ref_list', 'ajax');
	} else {
		$this->redirect(array('action'=>'index', $app_id));	
	}
}
		
	/**
	*Delete a Reference.
	*/
function delete($id=null) {

	if (!$id) {
			$this->Session->setFlash(__('Invalid id for Reference', true), 'flash_failure');
			$this->redirect($this->referer());
		}
		
		$this->Reference->id = $id;
		$app_id = $this->Reference->field('application_id');
		
		if(!$this->Reference->isEvaluated($id) && $this->Reference->delete($id)) {
			$stat = 0;
			if ($this->Reference->find('count', array(
																'conditions' => array(
																'Reference.application_id' => $app_id))) > 0) {
				$stat= 1;
			}	
			$this->Application->change_status($app_id, 'references', $stat, '');
		} else {
			$this->Session->setFlash(__('Error deleting reference.', true), 'flash_failure');
		}
		
		$data = $this->Reference->findAllByApplicationId($app_id, array(
																											'id', 'firstname', 'lastname', 'phone', 'email', 'complete'), 
																											null, null, null, 0);
		$this->set('app_id', $app_id); 		
		$this->set(compact('data'));
		
		if ($this->RequestHandler->isAjax()) {
			$this->render('ref_list', 'ajax');
		} else {
			$this->redirect(array('action'=>'index', $app_id));	
		}
}

/**
* Fill out an evaluation
**/
function evaluate ($id=null, $uid= null) {
	
	if(!$this->Reference->checkAccess($id, $uid)) {
		return;
	}
	if (!empty($this->data)) {
		if (!$this->Reference->isEvaluated($this->data['Reference']['id']) 
				&& $this->Reference->save($this->data)) {
			$app_id = $this->Reference->field('application_id');
			if ($this->Reference->isComplete($app_id)) {
				$this->Application->change_status($app_id, 'references', 2, '');
			} else {
				$this->Application->change_status($app_id, 'references', 1, '');
			}
			if($this->Reference->isEvaluated()) {
				//generate the confirmation email to send.
				//Grab the email content.
				$message =  $this->_getContentMsg('reference_eval_email');
				//Now email the reference.
				if (!$this->_sendEmailMsg($this->Reference->field('email'), 
																 'UO Department of Psychology Online Recommendation Confirmation', 
																 $message, array( 
																 	'full_name' => $this->Application->field('firstname')
																								 . ' ' 
																								 . $this->Application->field('lastname'),
																	'eval_data' => $this->_generateEval($this->Reference->id)
																 )
					 		 								 ) 
			) {
					$this->Session->setFlash(__('Error sending confirmation email.', true), 'flash_failure');	 
				}
			}
			$this->Session->setFlash(__('Submission successful.', true), 'flash_success');
			
		} else {
			$this->Session->setFlash('There was a problem saving your submission please try again.' . 
			' If you continue to have problems please contact gradsec@psych.uoregon.edu.','flash_failure');
		}
	}

	$this->data = $this->Reference->find('first', array('conditions' => array('Reference.uid' => $uid), 
																											'fields' => $this->lightFields));
	
	$this->set('info', $this->_getContentMsg('references_eval_info'));
	$this->layout = 'eval';
}

/*
* Add, Remove, or update a Reference letter.
**/
function viewLetter ($id=null, $uid=null) {
		//do the find...This view sets headers and presents the content.
		if (!($this->Auth->user('group_id') == 1 || $this->Auth->user('group_id') == 3)
				&& (!$this->Reference->checkAccess($id, $uid)
						|| $this->Reference->field('complete', array('Reference.id' => $id)))) {
			$this->redirect(array('action' => 'evaluate'));
		}
		
		$this->set('file', $this->Reference->read(array('content', 
																										 'mime_type', 
																										 'file_name', 
																										 'file_size'), $id));
		$this->render('view', 'file');
}

/*
* Add, Remove, or update a Reference letter.
**/
function deleteLetter ($id=null, $uid = null) {
	
	//do a query here to remove contents of file related details.
	if (!$this->Reference->checkAccess($id, $uid) 
			|| $this->Reference->field('complete', array('Reference.id' => $id))) {
			$this->redirect(array('action' => 'evaluate'));
	}
		
	$this->Reference->query("UPDATE `references` SET `content` = '', `mime_type` ='', `file_name` = '', `file_size` = '' WHERE" .
													" `references`.`id` = ${id}");
													
	$this->redirect(array('controller' => 'References', 'action' => 'evaluate',
												$id, $uid));
}
 

function adminComplete($app_id = null) {

	if(!empty($this->data)) {
		
		$error= false;
		$msg= '';
		foreach ($this->data['Reference'] as $key => $ref) {
			if (isset($ref['update']) && $ref['update'] == 1) {
				unset($ref['update']);
				if($ref['content']['error'] == 4) unset($ref['content']);
				if(!$this->Reference->save($ref)) {
					$error = true;
					$msg = "error saving ${ref['id']} <br />";
				}
				$this->Reference->id == null;
			} // end if update checked.
		} //end foreach.
		
		if ($this->Reference->find('count', array('conditions' => array('Reference.application_id' => $app_id,
																																		'Reference.complete = 1'))) >= 3) {
			$this->Application->change_status($app_id, 'references', 2, '');
		} else {
			$this->Application->change_status($app_id, 'references', 1, '');
		}
		
		if ($error) {
			$this->Session->setFlash($msg, 'flash_failure');
		}
		$this->Session->setFlash('Successfuly updated reference!', 'flash_success');
	} //end else data.
	
	$this->data= $this->Application->findById($app_id, null, null, 1);
}// end function adminComplete.
 	
function adminEmail($ref_id = null) {
	
	if($ref_id) {
		$this->data = $this->Reference->find('first', array('conditions' => array('Reference.id' => $ref_id), 
																																							'fields' => $this->lightFields));
		if($this->data['Reference']['use_web']) {
			//Grab the email content.
			$message =  $this->_getContentMsg('reference_request_email');
			//Now email the student.
			if (!$this->_sendEmailMsg($this->data['Reference']['email'], 
							  'UO Department of Psychology Online Recommendation Request', 
							  $message, array( 
																 	'full_name' => $this->data['Application']['firstname']
																								 . ' ' 
																								 . $this->data['Application']['lastname'],
																	'base_url' => FULL_BASE_URL,
																	'url' => $this->data['Reference']['id'] . '/' . $this->data['Reference']['uid']
																 )
					 		 								 )
			) {
				$this->Session->setFlash(__('Unable to send reference request email.', true), 
																			'flash_failure');
				$this->redirect(array('action' => 'adminEmail'));
			} else {
				$this->Reference->query('UPDATE `references` SET `email_sent` = 1 WHERE id = '. $ref_id . ';');
				$this->Session->setFlash(__('Email sent successfully.', true), 
																			'flash_success');
				$this->redirect(array('action' => 'adminEmail'));
			}
		}
	}	
	
	$this->paginate = array(
		'conditions' => array(
			'Reference.email_sent' => false, 
			'Reference.use_web' => true
		),		
		'fields' => array('id', 'created', 'lastname', 'firstname', 'email')
	);
		
	$this->data = $this->paginate('Reference');
	
}
 	
/*
* Generate a pdf of the completed form.
*/
function pdf($ref_id) {
 		
 		$this->data = $this->Reference->findById($ref_id);
 		
 		
 		Configure::write('debug',0);
 		$filename = $this->data['Reference']['lastname'] . '_evaluation_for_';
		$filename .= $this->data['Application']['lastname'] . '_' . $this->data['Application']['firstname']; 
 		
 		$this->set('filename', $filename);
 		
 		$this->render(null, 'file');
 	}
 	
///////////////////////////////////////////////////////////////////////////////////////////
//Private Functions
function _generateToken() {
	return sha1(uniqid(rand(), true));
}

function _generateEval($id) {
	
	$data = $this->Reference->find('first', array("conditions" => array("Reference.id" => $id),
																				"fields" => $this->lightFields));  
	$content = null;
	$fullname = $data["Application"]["firstname"] . " " . $data["Application"]["lastname"];
	$content .= "Completed on: " . date("M d, Y -- h:ia, T") . "\n";
	$content .= $fullname . (($data["Reference"]["ferpa_waived"])? " has waived":" has not waived");
	$content .= " his/her right to view this evaluation under FERPA.\n"; 
	$content .= "Attached Recommendation Letter Filename:\n\n";
	if (empty($data["Reference"]["file_name"])) {
		$content .= "No File attached";
	} else {
		$content .= $data["Reference"]["file_name"]. "\n\n";
	}
	$content .= "Your Contact Information:\n\n";
	$content .= $data["Reference"]["firstname"] . " ";
	$content .= $data["Reference"]["lastname"] . "\n";
	$content .= $data["Reference"]["title"] . "\n";
	$content .= $data["Reference"]["phone"] . "\n\n";
	$content .= "Evaluation form for " . $fullname .":\n\n";
	$content .= "How long and in what capacity have you known the applicant?\n\n";
	$content .= $data["Reference"]["knowledge_length"] . "\n\n";
	$content .= "Do you have a graduate program? ";
	$content .= ($data["Reference"]["has_grad_prog"])? ($data["Reference"]["has_grad_prog"]== 2)? "Yes\n\n":"No\n\n":"\n\n";
	$content .= "If yes, and if the decision were entirely up to you, would you admit the applicant into your program? ";
	$content .= ($data["Reference"]["would_admit"])? ($data["Reference"]["would_admit"]== 2)? "Yes\n\n":"No\n\n":"\n\n";
 	$content .= "If no, Why not?\n\n";
	$content .= $data["Reference"]["not_admit_info"] . "\n\n";
	$content .= "Please rate the applicant on the following qualities:\n\n";
	$content .= "Intellectual ability: ". $data["Reference"]["intel_ability"] . "\n";
	$content .=	"Academic preparation: ". $data["Reference"]["academic_prep"] . "\n";
	$content .=	"Maturity/Responsibility: ". $data["Reference"]["maturity"]. "\n";
	$content .=	"Interpersonal skills: " . $data["Reference"]["interpersonal_skills"]. "\n";
	$content .=	"Oral communication skills: " . $data["Reference"]["oral_comm"]. "\n";
	$content .=	"Written communication skills: ". $data["Reference"]["written_comm"]. "\n";
	$content .=	"Ability to complete tasks: ". $data["Reference"]["finishes_tasks"]. "\n";
	$content .=	"Creative, integrative thinking: ". $data["Reference"]["creative_think"]. "\n";
	$content .=	"Ability to work independently: ". $data["Reference"]["independent_work"]. "\n";
	$content .=	"(Clinical applicants only) Ability to handle clinical issues in a professional manner: ". $data["Reference"]["professional_clinic"] ."\n\n";
	$content .= "Compared to other graduate students, please rate the applicant on the following:\n\n";
	$content .= "Motivation: ". $data["Reference"]["motivation"]. "\n";
	$content .= "Originality: ". $data["Reference"]["originality"]. "\n";
	$content .=	"Initiative: ". $data["Reference"]["initiative"]. "\n"; 
	$content .=	"Critical thinking: ". $data["Reference"]["critical_thinking"]. "\n";
	$content .=	"Emotional stability: ". $data["Reference"]["emot_stability"]. "\n";
	$content .=	"Perseverance: ". $data["Reference"]["perseverance"]. "\n\n";
	
	$content .= "Overall this applicant is: ". $data["Reference"]["overall"]. "\n\n";
	
	$content .= "Please contact us with any questions or concerns:\n\n";
	$content .= "Thank you!\n\n";
	$content .= "Lori Olsen\n";
	$content .= "Graduate Secretary\n"; 
	$content .= "Department of Psychology";
	$content .= "1227 University of Oregon (Straub Hall)\n";
	$content .= "Eugene, OR 97403\n";
	$content .= "541.346.5060\n";
	return $content;
}

}//end controller.
